package com.xxb.service.user.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.xxb.service.user.mapper.UserMapper;
import com.xxb.service.user.model.dto.LoginReqDTO;
import com.xxb.service.user.model.dto.LoginRespDTO;
import com.xxb.service.user.po.UserPO;
import com.xxb.service.user.service.UserService;
import com.xxb.service.user.service.WeixinLoginService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * @author RenGaoshuai
 * @date 2023/7/25 10:32
 * @description
 */
@Service
@Slf4j
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WeixinLoginService weixinLoginService;

    @Override
    public LoginRespDTO login(LoginReqDTO reqDTO) {
        String openId = weixinLoginService.getOpenId(reqDTO.getCode());
        log.info("用户的openid为：{}", openId);

        UserPO openidUser = userMapper.queryByOpenid(openId);
        if (Objects.isNull(openidUser)) {
            //自动注册
            UserPO dbUser = new UserPO();
            dbUser.setOpenid(openId);
            dbUser.setUnionid(openId);
            dbUser.setNickname("小半");
            dbUser.setUsername("小半");
            dbUser.setAvatar("/images/avatar/01.jpg");


            dbUser.setSign("Ta很懒，什么都没留下~~~");
            dbUser.setSex(1);
            dbUser.setTelephone("");
            dbUser.setVip(1);
            dbUser.setCron(50);
            dbUser.setStudydays(1);
            dbUser.setIsDelete(0);
            dbUser.setForbbiden(0);
            dbUser.setRole("normal");
            dbUser.setPassword("");
            dbUser.setFans(0);
            dbUser.setGznums(0);

            int insert = userMapper.insert(dbUser);
            if (insert > 0) {
                log.info("openid:{}用户自动注册成功", openId);
            }
            return BeanUtil.copyProperties(dbUser, LoginRespDTO.class);

        }

        return BeanUtil.copyProperties(openidUser, LoginRespDTO.class);

    }
}
